package com.x.wcrm.assemble.control.service;

import com.google.gson.*;
import com.x.base.core.container.EntityManagerContainer;
import com.x.base.core.container.factory.EntityManagerContainerFactory;
import com.x.base.core.entity.annotation.CheckPersistType;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.base.core.project.tools.ListTools;
import com.x.wcrm.assemble.control.Business;
import com.x.wcrm.assemble.control.tools.ClassPathResource;
import com.x.wcrm.core.entity.WCrmConfig;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class SystemConfigPersistService {
    private Logger logger = LoggerFactory.getLogger( SystemConfigPersistService.class );

    /**
     * 初始化所有的系统设置
     * @throws Exception
     */
    public void initSystemConfig() throws Exception {
        Business business = null;
        try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
            business = new Business(emc);
            List<WCrmConfig> configs = business.configFactory().ListConfigsWithType("线索");
            if(ListTools.isEmpty(configs)){
                logger.info("crm---系统检测到crm未初始化配置");
                ClassPathResource resource = new ClassPathResource("/config.json");
                InputStream in = resource.getInputStream();
                if (in != null) {
                    String configStr = readToString(in);
                    JsonParser parser = new JsonParser();
                    JsonArray jsonArray = parser.parse(configStr).getAsJsonArray();
                    //logger.info("jsonArray============"+jsonArray.size());
                    Gson gson = new Gson();
                    List<WCrmConfig> configList = new ArrayList<>();
                    for (JsonElement o : jsonArray) {
                        //使用GSON，直接转成Bean对象
                        WCrmConfig wc = gson.fromJson(o, WCrmConfig.class);
                        configList.add(wc);
                    }
                    if(ListTools.isNotEmpty(configList)){
                        logger.info("crm---初始化配置开始");
                        emc.beginTransaction(WCrmConfig.class);
                        for(WCrmConfig wconfig : configList){
                            emc.persist(wconfig, CheckPersistType.all);
                        }
                        emc.commit();
                        logger.info("crm---初始化配置结束");
                    }
                }
            }
        }catch ( Exception e ) {
            throw e;
        }
    }

    public String readToString(InputStream input) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int n = 0;
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
        }
        return new String(output.toByteArray(), "UTF-8");
    }
}
